/**
 * @Author: ls-mac
 * @Date:   2018-10-22 22:51:24
 * @Last modified by:   ls-mac
 * @Last modified time: 2020-07-02 19:42:43
 */

export default {
  namespace: 'global',

  state: {
    collapsed: false,
    currentUser: {},
    panes: [],
    activeKey: '',
  },

  effects: {
    *fetchCurrent({ callback }, { call, put }) {},
    *changePwd({ payload, callback }, { call }) {},

    *addNewPage({ payload, callback }, { call, put }) {
      yield put({
        type: 'saveAddNewPage',
        payload,
      });
    },

    *selectMenu({ payload, callback }, { call, put }) {
      yield put({
        type: 'saveSelectMenu',
        payload,
      });
    },
    *changeActiveKey({ payload, callback }, { call, put }) {
      yield put({
        type: 'saveChangeActiveKey',
        payload,
      });
    },
    *deleteActiveKey({ payload, callback }, { call, put }) {
      yield put({
        type: 'saveDeleteActiveKey',
        payload,
      });
      if (callback) callback();
    },
  },

  reducers: {
    changeLayoutCollapsed(state, { payload }) {
      return {
        ...state,
      };
    },
    saveCurrentUser(state, { payload }) {
      const { tenantId } = payload;
      return {
        ...state,
      };
    },
    saveSelectMenu(state, { payload }) {
      const { panes } = state;
      if (panes instanceof Array && payload.key) {
        if (panes.indexOf(payload.key) < 0) {
          panes.push(payload.key);
        }
      }

      return {
        ...state,
        panes,
        activeKey: panes.indexOf(payload.key),
      };
    },

    saveChangeActiveKey(state, { payload }) {
      return {
        ...state,
        activeKey: payload,
      };
    },
    saveAddNewPage(state, { payload }) {
      const { panes, activeKey } = state;
      let newList = [...new Set([...panes, `${payload}`])];

      return {
        ...state,
        activeKey: newList.indexOf(`${payload}`),
        panes: newList,
      };
    },
    saveDeleteActiveKey(state, { payload }) {
      const { panes, activeKey } = state;

      let newIndex = 0;

      if (payload - 0 > activeKey - 0) {
        newIndex = activeKey;
      }
      if (payload - 0 == activeKey - 0) {
        newIndex = payload - 0 == panes.length - 1 ? activeKey - 1 : activeKey;
      }
      if (payload - 0 < activeKey - 0) {
        newIndex = activeKey - 1;
      }

      let list = panes.filter((v, i) => {
        if (i != payload) {
          return v;
        }
      });

      return {
        ...state,
        activeKey: newIndex,
        panes: list,
      };
    },
  },
};
